// NeLNS - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
// Copyright (C) 2010  Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifndef LS_FES_MGR_H
#define LS_FES_MGR_H

#include <server_share/msg_struct_login.h>
#include <vector>
namespace LS
{

class CFesMgr : public NLMISC::CSingleton<CFesMgr>
{
public:

	CFesMgr():_CurrPlayers(0),_MaxPlayres(0)
	{
	}

	MSG_STR::CFrontEnd* findBestFes()
	{
		MSG_STR::CFrontEnd* pFes = NULL;
		if ( !_vctFrontEnd.empty() )
		{
			for ( uint i=0; i<_vctFrontEnd.size(); ++i )
			{
				if ( pFes == NULL )
				{
					if ( _vctFrontEnd[i].CurrPlayers < _vctFrontEnd[i].MaxPlayers )
					{
						pFes = &_vctFrontEnd[i];
					}
					continue;
				}
				else if ( pFes->CurrPlayers > _vctFrontEnd[i].CurrPlayers )
				{
					pFes = &_vctFrontEnd[i];
				}
			}
		}
		return pFes;
	}

	MSG_STR::CFrontEnd* findFes( NLNET::TServiceId SId )
	{
		MSG_STR::CFrontEnd* pFes = NULL;
		for ( uint i=0; i<_vctFrontEnd.size(); ++i )
		{
			if ( _vctFrontEnd[i].SId == SId )
			{
				pFes = &_vctFrontEnd[i];
				break;
			}
		}
		return pFes;
	}

	void removeFes( NLNET::TServiceId SId )
	{
		std::vector<MSG_STR::CFrontEnd>::iterator iter;

		for ( iter = _vctFrontEnd.begin(); iter!=_vctFrontEnd.end(); ++iter )
		{
			if ( iter->SId == SId )
			{
				_MaxPlayres -= iter->MaxPlayers;
				_vctFrontEnd.erase(iter);
				break;
			}
		}
	}

	bool addFes( MSG_STR::CFrontEnd& fes )
	{
		bool res = false;
		if ( findFes(fes.SId) == NULL )
		{
			_MaxPlayres += fes.MaxPlayers;
			_vctFrontEnd.push_back(fes);
			res = true;
		}
		return res;
	}

	void   resetCurrPlayers()
	{
		_CurrPlayers = 0;
		for ( uint i=0; i<_vctFrontEnd.size(); ++i )
		{
			_CurrPlayers += _vctFrontEnd[i].CurrPlayers;
		}
	}

	void incCurrPlayers()	{ ++_CurrPlayers; }

	//uint32 getCurrPlayers()	{	return _CurrPlayers;	}
	//uint32 getMaxPlayers()	{	return _MaxPlayres;		}

	bool   isFull()	{	return _CurrPlayers >= _MaxPlayres;	}

private:
	std::vector<MSG_STR::CFrontEnd>  _vctFrontEnd;
	uint32     _CurrPlayers;
	uint32     _MaxPlayres;
};

#define  FesMgr  CFesMgr::instance()
}
#endif // LS_FES_MGR_H

/* End of fes_mgr.h */
